<?php

require_once PATH_FFWD.'core/helpers.php';


if(!defined('LOCATION_ROOT'))define('LOCATION_ROOT','');
define('CONSOLE_MODE',0);
define('BR','<br/>');
define('HR','<hr/>');
define('NBSP','&nbsp;');
define('ACTION','__ACTION');
define('MODULE','__MODULE');
define('APPLICATION','__APPLICATION');
define('P0','__0');
define('P1','__1');
define('P2','__2');
define('P3','__3');
define('P4','__4');
define('P5','__5');
define('P6','__6');
define('P7','__7');
define('P8','__8');
define('P9','__9');

$default_request_data=Array(
		APPLICATION=>'frontend',
		MODULE=>Array('default'), 
		ACTION=>'index',		
	);

function get_module_filename($request_data){
	if(!isset($request_data[APPLICATION]))$request_data[APPLICATION]=$_SERVER['REQUEST_DATA'][APPLICATION];
	$r=PATH_APPS.$request_data[APPLICATION];
	if(!is_array($request_data[MODULE]))throw new Exception('request_data[MODULE] must be an array');
	foreach($request_data[MODULE] as $m)$r.='/module.'.$m;
	return $r.'.php';	
}

function __parse_location_new($location){
	$lrl=strlen(LOCATION_ROOT);
	if($lrl && substr($location,0,$lrl)==LOCATION_ROOT)$location=substr($location,$lrl);
	//if(DEBUG)print_var($location,'<hr>__parse_location_new');	
	if(!$location)$location='/index.html';	
	$d=parse_url($location);
	$r=Array();
	$path=explode('/',$d['path']);	
	if(substr($path[1],-4)!='.php')$path[0]='frontend.php';else	array_shift($path);//app name on index 0
	$r[APPLICATION]=strtolower(substr(array_shift($path),0,-4));
	if(substr($r[APPLICATION],-4)=='_dev')$r[APPLICATION]=substr($r[APPLICATION],0,-4);	
	$r[MODULE]=Array();
	$p=PATH_APPS.$r[APPLICATION].'/';
	$was_dir=0;
	
	if(!empty($path))while(true){		
		$p.='module.'.$path[0];
		if(is_file($p.'.php')){
			$was_dir=0;$r[MODULE][]=array_shift($path);
			break;			
		}else if(is_dir($p)){	
			$was_dir=1;$r[MODULE][]=array_shift($path);
			$p.='/';		
		}else{
			if($was_dir)$r[MODULE][]='default';
			break;
		}			
	}
	$i=0;
	while(count($path)>1){ 
		$r['__'.$i++]=array_shift($path);
	}
	if(isset($d['query'])){
		$d['query']=explode('&',$d['query']);
		foreach($d['query'] as $k=>$v){
			$e=explode('=',$d['query'][$k]);
			$r[$e[0]]=(isset($e[1])?$e[1]:NULL);
		}
	};
	if(!empty($path)){
		$r[ACTION]=substr($path[0],0,strrpos($path[0],'.'));
	};
	
	$r=array_merge($GLOBALS['default_request_data'],$r);
	if(empty($r[MODULE]))$r[MODULE]=$GLOBALS['default_request_data'][MODULE];
	
	
	//if(DEBUG)print_var($r,'parse_location_new\'s return value');echo "<hr>";
	return $r;
}

function __parse_location($location){
	if(!$location)$location='/';
	if(substr($location,-4)=='.php')$location.='/index.html';
	if($location[0]=='/')$location=substr($location,1);
	$d=parse_url($location);
	$d['p']=explode('/',$d['path']);
	$d['r']=Array();
	preg_match('/(.*).html/',array_pop($d['p']),$d['r'][ACTION]);
	if(!isset($d['r'][ACTION][1]))throw new Exception('ACTION not defined');
	$d['r'][ACTION]=$d['r'][ACTION][1];		
	$f=array_shift($d['p']);
	if(preg_match('/(.*)\.php/',$f,$a)){
		$d['r'][APPLICATION]=$a[1];$d['r'][MODULE]=array_shift($d['p']);
	}else	$d['r'][MODULE]=$f;
	if(!$d['r'][MODULE])$d['r'][MODULE]='main';
	if(!isset($d['r'][APPLICATION]))$d['r'][APPLICATION]='frontend';	
	foreach($d['p'] as $k=>$v)$d['r']['__'.$k]=$v;
	ksort($d['r']);	
	if(isset($d['query']))foreach(explode('&',$d['query']) as $g){$g=explode('=',$g);$d['r'][$g[0]]=(isset($g[1])?$g[1]:1);};	
	return $d['r'];
}

function parse_location($location){
	try{
		return __parse_location_new($location);
	}catch(Exception $e){
		throw new Exception('Unable to parse location: '.$location);
	}
}

function link_for_old($p=Array(),$location=0){
	if(!isset($_SERVER['REQUEST_DATA']))$_SERVER['REQUEST_DATA']=parse_location($_SERVER['REQUEST_URI']);
	if($location)$c=parse_location($location);else $c=$_SERVER['REQUEST_DATA'];	
	foreach($c as $k=>$v){if(!isset($p[$k]))$p[$k]=$v;else if(($p[$k]!=$c[$k]))break;};	
	$r='/';if($p[APPLICATION]!='frontend')$r.=$p[APPLICATION].'.php/';unset($p[APPLICATION]);
	$r.=$p[MODULE].'/';unset($p[MODULE]);
	for($i=0;;$i++){if(!isset($p['__'.$i]))break;$r.=$p['__'.$i].'/';	unset($p['__'.$i]);};
	$r.=$p[ACTION].'.html?';
	unset($p[ACTION]);
	if(count($p))foreach($p as $k=>$v)$r.="$k=$v&";
	return substr($r,0,-1);
};

function buildURL($p){
	global $default_request_data;
	$url='/';
	if(DEBUG || $p[APPLICATION]!=$default_request_data[APPLICATION])$url.=$p[APPLICATION].(DEBUG?'_dev':'').'.php/';
	foreach($p[MODULE] as $k=>$v){
		if($v=='default')break;
		$url.=$v.'/';
	};
	for($i=0;$i<10;$i++){
		if(!isset($p['__'.$i]))break;
		$url.=$p['__'.$i].'/';
	};
	$url.=$p[ACTION].'.html';
	return $url;
}

function array_to_urlgetparam($params){
	$o='?';
	foreach($params as $k=>$v)$o.=urlencode($k).'='.urlencode($v).'&';
	return substr($o,0,-1);	
}

function array2urlgetparam($params){return array_to_urlgetparam($params);};
function array2get($params){return array_to_urlgetparam($params);};

function link_for($p,$getparams=Array()){
	if($p===NULL){
		$a=explode('?',$_SERVER['REQUEST_URI']);
		return $a[0].array_to_urlgetparam($getparams);
	};
	if(is_array($p)){
		throw new Exception('This is the new version of LINK_FOR, call it with a string route!!');
	}
	$c_upstep=$p[0]=='/'?999:0;
	$p=explode('/',$p);
	$new=Array();
	if($p[0] && $p[0]!='..'){ //  nem '/'-el kezdĂ„â€šĂ˘â‚¬ĹľÄ‚â€žĂ˘â‚¬Â¦Ă„â€šĂ‹ÂÄ‚ËĂ˘â‚¬ĹˇĂ‚Â¬Ă„ĹąÄąÄ˝Ă‹ĹĄdik		
		foreach($_SERVER['REQUEST_DATA'] as $k=>$v){			
			$new[$k]=$v;
			if($k==MODULE){
				foreach($v as $k2=>$v2)$new[MODULE][$k2]=$v2;
				break;
			};					
		}
		$i=0;
		while(count($p)>1)$new['__'.$i++]=array_shift($p);
		$new[ACTION]=$p[0];
	}else{ //
		if(!$c_upstep){
			for($i=0;!empty($p);$i++){
				if($p[0]!='..')break;
				$c_upstep++;
				array_shift($p);
			}
		}else{
			array_shift($p);
		}
		foreach($_SERVER['REQUEST_DATA'] as $k=>$v){			
			
			if($k==MODULE){
				$new[$k]=Array();
				$stopat=count($v)-$c_upstep;
				if($stopat<0)$stopat=0;
				for($i=count($v)-1;$i>=$stopat;$i--){
					unset($v[$i]);
				}
				foreach($v as $modulename)$new[MODULE][]=$modulename;
				break;	
			};	
			$new[$k]=$v;				
		};
		$i=0;
		while(count($p)>1)$new['__'.$i++]=array_shift($p);
		$new[ACTION]=$p[0];
	};	
	if(!isset($new[APPLICATION]))$new[APPLICATION]=$GLOBALS['default_request_data'][APPLICATION];
	if(empty($new[MODULE]))$new[MODULE]=$GLOBALS['default_request_data'][MODULE];
	if(!isset($new[ACTION]))$new[ACTION]=$GLOBALS['default_request_data'][ACTION];

	return LOCATION_ROOT.buildURL($new).array_to_urlgetparam($getparams);
}

function change_url_keys($url,$keys){
	$url=explode('?',$url);
	if(!isset($url[1]))$url[1]='';
	$url[1]=explode('&',$url[1]);
	foreach($url[1] as $k=>$v){
		$v=explode('=',$v);
		if(!isset($v[1]))$v[1]='';
		unset($url[1][$k]);
		$url[1][$v[0]]=$v[1];	
	};
	foreach($keys as $k=>$v)$url[1][$k]=$v;
	$r=$url[0].'?';
	foreach($url[1] as $k=>$v){
		if($k)$r.=$k.'='.$v.'&';
	}			
	return substr($r,0,-1);
}
